# coding = utf-8
# Author = Ann
# Start Date: 2023/6/27


import ast
import json
import os.path


def get_dir(test_num, allure_path):
    # 第一次报告生成位置
    first_path = os.path.join(allure_path, str(test_num))
    # 检查路径是否存在
    if os.path.exists(first_path):
        # 获取并排序目录中的所有文件
        allresultdir = os.listdir(allure_path)
        allresultdir.sort(key=int)
        # 获取最新的历史文件
        history_file = os.path.join(allure_path, str(int(allresultdir[-1].lstrip('0'))), "html", "widgets",
                                    "history-trend.json")
        with open(history_file, "r") as f:
            data = f.read()
        return int(allresultdir[-1].lstrip('0')) + 1, data
    else:
        os.makedirs(os.path.join(allure_path, '1'))
        return 1, None


def get_history(test_num, old_data, allure_path):
    if old_data is not None:
        history_file = os.path.join(allure_path, str(test_num), "html", "widgets", "history-trend.json")
        with open(history_file) as f:
            data = json.load(f)
            # data[0]["test_num"] = int(test_num)
            return data
    else:
        first_history_file = os.path.join(allure_path, str(test_num), "html", 'widgets', 'history-trend.json')
        with open(first_history_file) as f:
            data = json.load(f)
            # data[0]['test_num'] = 1
            return data


def update_file(test_num, allure_path):
    if test_num != 1:
        old_data = os.path.join(allure_path, str(test_num - 1), "html", "widgets", "history-trend.json")
        new_data = os.path.join(allure_path, str(test_num), "html", "widgets", "history-trend.json")
        with open(old_data) as f:
            old = json.load(f)
            dict = []
            for i in range(len(old)):
                dict.append(old[i])
            with open(new_data) as f:
                r = f.read()
                new_list = ast.literal_eval(r)
                for i in range(len(dict)):
                    new_list.append(dict[i])
            with open(new_data, 'w') as f:
                json.dump(new_list, f)
